package chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class NioChat {
    private static List<SocketChannel> channels=new ArrayList<>();
    private static ByteBuffer buffer=ByteBuffer.allocate(1024);
    public static void main(String[] args) throws Exception{
        ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(9001));
        serverSocketChannel.configureBlocking(false);
        while (true){
            SocketChannel channel = serverSocketChannel.accept();
            if(channel!=null){
                channel.configureBlocking(false);
                channels.add(channel);
//                System.out.println(channel.socket().getPort());
            }
            for (int i = 0; i < channels.size(); i++) {
                SocketChannel chan = channels.get(i);
                int len = chan.read(buffer);
                String info = new String(buffer.array(), 0, len);
                buffer.clear();
                if(len>0){
                    if(info.startsWith("bye")){
                        chan.close();
                        channels.remove(chan);
                    }
                    send(chan,info);
                }
            }
        }
    }
    private static void send(SocketChannel channel,String info){

//        channels
//                .stream().map(item->item.socket().getPort())
//                .filter()
//                .collect(Collectors.toList())
//                .forEach(port-> System.out.println(port)));
        for (int i = 0; i < channels.size(); i++) {
            SocketChannel channel1 = channels.get(i);
            if(channel1!=channel){
                try {
                    channel1.write(ByteBuffer.wrap(info.getBytes()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
